// 使用http
/* // 引入node 内置的http 模块
const http = require('http');

// 默认地址
// const hostname = '127.0.0.1';
// 要监听的端口号
const port = 3333;

// 创建 web 服务器 得到一个服务对象
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html;charset=utf-8');
    res.end('<h1>你好  3333</h1>');
});

server.listen(port, () => {
    console.log('监听端口', port);
}); */

//使用express
//导入包
const express = require('express');
//创建服务器对象
const app = express();
//端口号
const port = 3000;
// post 请求
const bodyParser = require('body-parser');
// 引入加密方法
const jwt = require('jsonwebtoken');

//增加头部信息解决跨域问题
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");//设置响应头，*表示任何地址都亦可以访问
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("X-Powered-By", ' 3.2.1');
    next();
});

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.all('/queryServerInfo', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    let zhanghao = req.body;
    let queryFlag = true;
    let msg = "";
    let jsonstr = [
        {
            username: "guowei",
            pwd: "gw060113"
        },
        {
            username: 'admin',
            pwd: '123456'
        }
    ];
    let token = "";
    jsonstr.filter((person) => {
        person.username === zhanghao.username ? queryFlag = true : queryFlag = false
        if (queryFlag) {
            person.pwd === zhanghao.password ? queryFlag = true : queryFlag = false
            if (queryFlag) {
                let name = person.name;
                token = jwt.sign({ name }, "login123", { expiresIn: 60 * 60 * 24 });
                msg = "登录成功";
            } else {
                msg = "密码错误";
            }
        } else {
            msg = "该用户不存在";
        }
    })
    res.send(JSON.stringify({ queryFlag: queryFlag, msg: msg, token: 'Bearer' + token }));
})

//监听端口
app.listen(port, () => {
    console.log("3000端口监听中");
})